﻿using StardewModdingAPI;
using StardewValley;
using Microsoft.Xna.Framework;

namespace WorseGame.Content
{
    public class 移动体力消耗(IMonitor 监视器, IModHelper 助手)
    {
        private readonly IMonitor 监视器 = 监视器;
        private readonly IModHelper 助手 = 助手;
        private double 累计移动距离 = 0;
        private Vector2 上次位置 = Vector2.Zero;

        public void Initialize()
        {
            助手.Events.GameLoop.UpdateTicked += 更新时触发;
            助手.Events.GameLoop.SaveLoaded += 存档加载时;
            助手.Events.GameLoop.DayStarted += 每日开始时;
        }

        private void 存档加载时(object? sender, StardewModdingAPI.Events.SaveLoadedEventArgs e)
        {
            if (Game1.player != null)
            {
                上次位置 = Game1.player.Position;
            }
        }

        private void 每日开始时(object? sender, StardewModdingAPI.Events.DayStartedEventArgs e)
        {
            累计移动距离 = 0;
            if (Game1.player != null)
            {
                上次位置 = Game1.player.Position;
            }
        }

        private void 更新时触发(object? sender, StardewModdingAPI.Events.UpdateTickedEventArgs e)
        {
            if (Context.IsWorldReady && Game1.player != null && e.IsMultipleOf(30))
            {
                if (Game1.player.Position != 上次位置)
                {
                    float 移动距离 = Vector2.Distance(上次位置, Game1.player.Position);
                    累计移动距离 += 移动距离;
                    if (累计移动距离 >= 100)
                    {
                        int 消耗次数 = (int)(累计移动距离 / 100);
                        累计移动距离 %= 100;
                        消耗体力(消耗次数);
                    }
                    上次位置 = Game1.player.Position;
                }
            }
        }

        private static void 消耗体力(int 次数)
        {
            if (Game1.player.stamina > 0)
            {
                float 单次消耗量 = 0.5f;
                float 总消耗量 = 单次消耗量 * 次数;
                总消耗量 = Math.Min(总消耗量, Game1.player.stamina);
                Game1.player.stamina -= 总消耗量;
            }
        }

        public void Dispose()
        {
            助手.Events.GameLoop.UpdateTicked -= 更新时触发;
            助手.Events.GameLoop.SaveLoaded -= 存档加载时;
            助手.Events.GameLoop.DayStarted -= 每日开始时;
        }
    }
}